# coding=utf8
# 全世界最帅的帅哥
from flask import request, g, current_app
from flask_restful import Resource, reqparse
from comment.utils.decorators import login_required
from comment.modules.user import User
from comment.modules.letter import LetterDetail, Letter
from comment.modules import db
from .serializer import LetterPaginateSerializer


class LetterResource(Resource):
    """
    发送消息的资源类
    """
    method_decorators = [login_required]

    def post(self):
        rp = reqparse.RequestParser()
        rp.add_argument("title", required=True)
        rp.add_argument("group")  # 群发时候的用户组
        rp.add_argument("rec_id")  # 单个用户发送时候的用户ID
        rp.add_argument("content", required=True)  # 发送内容

        args = rp.parse_args()
        title = args.title
        group = args.group
        rec_id = args.rec_id
        content = args.content

        # 发送消息的用户ID
        uid = g.user_id
        user = User.query.filter(User.id == uid).first()

        if group == "0" or group == "1":
            rec_list = User.query.filter(User.role == int(group)).all()
        else:  # 群发消息给所有人
            rec_list = User.query.all()

        # 单个用户发送消息
        if rec_id:
            rec_user = User.query.filter(User.id == rec_id).first()
            rec_list = [rec_user]

        # 遍历给每个用户发消息
        # 把消息详情插入到数据库中
        try:
            new_letter_detail = LetterDetail(title=title, detail=content)
            db.session.add(new_letter_detail)
            db.session.flush()

            for rec_user in rec_list:
                letter = Letter(sendID=user.username, recID=rec_user.id, detail_id=new_letter_detail.id)
                db.session.add(letter)

            db.session.commit()
            return {"msg": "发送消息成功"}
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return {"message": "发送消息失败", "resource": "letter", "class": "letter"}, 20001

    def get(self):
        """
        当前用户收到的消息列表(分页)
        :return:
        """
        # 拿到当前用户的id
        user_id = g.user_id
        rp = reqparse.RequestParser()
        rp.add_argument("cur_page", required=True)  # 访问的页号
        rp.add_argument("per_page", required=True)  # 每页显示的条数
        args = rp.parse_args()
        cur_page = int(args.cur_page)
        per_page = int(args.per_page)
        user = User.query.filter(User.id == user_id).first()

        # 是pagination类型，包含分页的数据
        # 同时在items属性中包含了消息列表数据
        letter_list = Letter.query.filter(Letter.recID == user_id).paginate(page=cur_page, per_page=per_page,
                                                                            error_out=False)
        dict_data = LetterPaginateSerializer(letter_list).to_dict()
        return {"msg": "ok!", "data": dict_data}

    def delete(self):
        """
        删除站内信
        :return:
        """

        rp = reqparse.RequestParser()
        rp.add_argument("message_id", required=True)
        args = rp.parse_args()
        message_id = args.message_id
        # 拿到站内信对象
        letter = Letter.query.filter(Letter.id == message_id).first()
        if letter:
            db.session.delete(letter)
            db.session.commit()
            return {"msg": "删除站内信成功！"}
        else:
            return {"message": "此信息不存在", "code": 20005}

    def put(self):
        """
        修改站内信的已读状态
        :return:
        """
        user_id = g.user_id
        rp = reqparse.RequestParser()
        rp.add_argument("message_id", required=True)
        args = rp.parse_args()
        message_id = args.message_id
        letter = Letter.query.filter(Letter.id == message_id).first()
        if letter:
            letter.state = 1
            db.session.commit()
            return {'msg': "ok"}
        else:
            return {'message': "此消息不存在", 'code': 20005}